package com.lidx.back.statistics.dao.impl;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Repository;

import com.lidx.back.statistics.dao.IMaterialDao;
import com.lidx.back.statistics.entity.MaterialPO;
import com.lidx.back.statistics.entity.MaterialUpdateRequestInfo;

@Repository
public class MaterialDaoImpl implements IMaterialDao {

	@Autowired
	private SessionFactory sessionFactory;
	//@Cacheable(value="materialPO")
	public List<MaterialPO> getAllMaterialPOs(String versionType, String versionNumber) {
		Session session = sessionFactory.getCurrentSession();
		StringBuffer sb = new StringBuffer("from MaterialPO where 1=1");
		if(StringUtils.isNotBlank(versionType)){
			sb.append(" and versionType = '").append(versionType).append("'");
		}
		if(StringUtils.isNotBlank(versionNumber)){
			sb.append(" and versionNumber = '").append(versionNumber).append("'");
		}
		Query query = session.createQuery(sb.toString());
		query.setCacheable(true);
		query.setCacheRegion("materialPO");
		List list = query.list();
		if(list.size()>0)
			return list;
		return null;
	}

	public List<MaterialPO> getRecommendMaterialPOs(String versionType,
			String versionNumber, String sex) {
		Session session = sessionFactory.getCurrentSession();
		Query query = session.createQuery("from MaterialPO where versionNumber = ? and versionType = ? and gender = ? and isRecommend = ?")
				.setString(0, versionNumber)
				.setString(1, versionType)
				.setString(2, sex)
				.setString(3, "1");
		List list = query.list();
		if(list.size()>0)
			return list;
		return null;
	}

	public void updateRequest(MaterialUpdateRequestInfo info) {
		Session session = sessionFactory.getCurrentSession();
		Query query = session.createQuery("update MaterialUpdateRequestInfo set versionNum=?,versionType = ? where id = 1")
				.setString(0, info.getVersionNum())
				.setString(1, info.getVersionType());
		query.executeUpdate();
	}

	public MaterialUpdateRequestInfo getRequestInfo() {
		Session session = sessionFactory.getCurrentSession();
		return (MaterialUpdateRequestInfo) session.get(MaterialUpdateRequestInfo.class, 1);
	}

	public void deleteMaterials(String versionType, String versionNumber) {
		Session session = sessionFactory.getCurrentSession();
		Query query = session.createQuery("delete from MaterialPO where versionNumber = ? and versionType = ? ")
				.setString(0, versionNumber)
				.setString(1, versionType);
		query.executeUpdate();
	}

	public void saveMaterial(MaterialPO materialPO) {
		Session session = sessionFactory.getCurrentSession();
		session.save(materialPO);
	}

}
